<template>
  <view class="moments-container">
    <scroll-view scroll-y class="moment-list-container" @scrolltolower="loadMore" refresher-enabled @refresherrefresh="handleRefresh">
      <view class="moment-list">
        <view class="moment-card" v-for="moment in moments" :key="moment.id">
          <view class="card-header">
            <image class="author-avatar" :src="safeImageUrl(moment.authorAvatar)" mode="aspectFill"></image>
            <view class="author-info">
              <text class="author-name">{{ moment.authorName || 'Unknown User' }}</text>
              <text class="moment-time">{{ formatTime(moment.createdAt) }}</text>
            </view>
          </view>
          <view class="card-body">
            <text class="moment-content">{{ moment.content }}</text>
            <view v-if="getImages(moment.images).length" class="moment-images">
              <image v-for="(image, index) in getImages(moment.images)" :key="index" class="moment-image" :src="getImageUrl(image)" mode="aspectFill"></image>
            </view>
          </view>
          <view class="card-footer">
            <view class="footer-action" @click="toggleLike(moment)">
              <text class="action-icon" :class="{ 'liked': isLiked(moment.id) }">赞</text>
              <text>{{ moment.likeCount }}</text>
            </view>
            <view class="footer-action" @click="goToDetail(moment)">
              <text class="action-icon">评论</text>
              <text>{{ moment.commentCount }}</text>
            </view>

          </view>
        </view>
      </view>
    </scroll-view>

    <view class="publish-fab" @click="goToPublish">
      <text>+</text>
    </view>
  </view>
</template>

<script>
import { mapState, mapActions, mapGetters } from 'vuex';
import imageHelper from '@/utils/imageHelper';

export default {
  data() {
    return {
      // This is a simplified client-side check. A real app might need more robust state management.
      userLikes: {}
    }
  },
  computed: {
    ...mapState('moments', ['moments']),
    ...mapGetters('user', ['userInfo']) // Assuming you have a user module with userInfo
  },
  onShow() {
    // Refresh data every time the page is shown
    this.fetchMoments();
  },
  methods: {
    ...mapActions('moments', ['fetchMoments', 'likeMoment', 'unlikeMoment']),
    ...mapActions('user', ['loadUserInfo']), // Action to load user info from storage
    
    isLiked(momentId) {
        // This provides instant UI feedback before the network request completes
        return this.userLikes[momentId];
    },
    
    async toggleLike(moment) {
        const momentId = moment.id;
        const currentlyLiked = this.isLiked(momentId);

        // Optimistically update UI
        this.$set(this.userLikes, momentId, !currentlyLiked);

        try {
            if (!currentlyLiked) {
                await this.likeMoment(momentId);
            } else {
                await this.unlikeMoment(momentId);
            }
        } catch (error) {
            // Revert UI on failure
            this.$set(this.userLikes, momentId, currentlyLiked);
            uni.showToast({ title: '操作失败', icon: 'none' });
        }
    },
    
    goToDetail(moment) {
        const momentStr = encodeURIComponent(JSON.stringify(moment));
        uni.navigateTo({
            url: `/pages/moments/detail?moment=${momentStr}`
        });
    },

    formatTime(timeStr) {
      // Basic time formatting
      return new Date(timeStr).toLocaleString();
    },
    goToPublish() {
      uni.navigateTo({
        url: '/pages/moments/publish'
      });
    },
    
    // 以下方法全部代理到 imageHelper
    getImages(imagesJson) {
      return imageHelper.parseImages(imagesJson);
    },

    getImageUrl(image) {
      return imageHelper.buildImageUrl(image);
    },

    safeImageUrl(url) {
      return imageHelper.safeImageUrl(url, 'avatar');
    }
  },
};
</script>

<style scoped>
.moments-container {
  height: 100vh;
  background-color: #fafafa;
}
.moment-list-container {
  height: 100%;
}
.moment-card {
  background-color: #fff;
  margin: 12rpx 16rpx;
  border-radius: 12rpx;
  padding: 16rpx;
  border: 1px solid #f0f0f0;
}
.card-header {
  display: flex;
  align-items: center;
}
.author-avatar {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  margin-right: 16rpx;
}
.author-name {
  font-weight: 500;
  font-size: 26rpx;
  color: #2c3e50;
}
.moment-time {
  font-size: 22rpx;
  color: #95a5a6;
}
.moment-content {
  margin: 16rpx 0;
  font-size: 26rpx;
  color: #555555;
  line-height: 1.5;
}
.moment-images {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8rpx;
}
.moment-image {
  width: 100%;
  height: 160rpx;
  border-radius: 8rpx;
}
.card-footer {
  display: flex;
  justify-content: space-around;
  margin-top: 16rpx;
  border-top: 1px solid #f8f9fa;
  padding-top: 8rpx;
}
.footer-action {
  display: flex;
  align-items: center;
  gap: 8rpx;
  font-size: 22rpx;
  color: #7f8c8d;
}
.footer-action .action-icon.liked {
  color: #e74c3c;
}
.publish-fab {
  position: fixed;
  bottom: 100rpx;
  right: 32rpx;
  width: 88rpx;
  height: 88rpx;
  background-color: #34495e;
  color: white;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 48rpx;
}
</style> 